<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use App\Models\SettingMessage;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class NoticeMessageController extends Controller
{
    /**
     * 自动配置模板消息
     */
    public function autoSetTplMessage()
    {
        $Wechat = $this->wechat();
        // 获取行业列表
        $_tpl_class = $Wechat->template_message->getIndustry();
        $_class = array();
        foreach ($_tpl_class as $_v) {
            $_class[] = implode("/", $_v);
        }
        unset($_tpl_class);
        try {
            if (!in_array("IT科技/IT软件与服务", $_class)) {
                throw new \Exception("未添加所属行业“IT科技/IT软件与服务”", 402);
            }
            // 获取当前数据库设置的模板消息id,删除当前设置的模板消息id
            $Setting = $this->getConfig();
            if ($Setting->message->await_check_tpl) {
                $Wechat->template_message->deletePrivateTemplate($Setting->message->await_check_tpl);
            }
            if ($Setting->message->result_check_tpl) {
                $Wechat->template_message->deletePrivateTemplate($Setting->message->result_check_tpl);
            }
            // 待审核提醒 模板编号 OPENTM418073234
            // 审核结果通知  模板编号 OPENTM417949050
            // 获取模板消息id
            $_await_data = $Wechat->template_message->addTemplate('OPENTM418073234');
            if ($_await_data["errcode"] != 0) {
                throw new \Exception($_await_data["errmsg"], 402);
            }
            $_result_data = $Wechat->template_message->addTemplate('OPENTM417949050');
            if ($_result_data["errcode"] != 0) {
                throw new \Exception($_result_data["errmsg"], 402);
            }
            $_data = array(
                "await_check_tpl" => $_await_data["template_id"],
                "result_check_tpl" => $_result_data["template_id"]
            );
            $_setting_id = $Setting = Setting::value("id");
            SettingMessage::where("setting_id", $_setting_id)->update($_data);
            return response(["data" => $_data]);
        } catch (\Exception $e) {
            return response(["message" => $e->getMessage()], $e->getCode());
        }
    }

    /**
     * 自动配置订阅消息id
     */
    public function autoSetSubscribeMessage()
    {
        try{
            $Wechat = $this->wechat();
            $_access_token = $Wechat->access_token->getToken();
            $_access_token = $_access_token["access_token"];
            $_subscribe_class = $this->getSubscribeClass($_access_token);
            if(!$_subscribe_class) {
                throw new \Exception("配置失败", 402);
            }
            if (!in_array("413",array_column((array)$_subscribe_class,"id"))) {
                throw new \Exception("请先在公众号内的订阅通知添加服务类目“IT科技>软件服务提供商”",402);
            }
            $Setting = $this->getConfig();
            if($Setting->message->result_check_sub) {
                $this->delSubscribeTpl($_access_token,$Setting->message->result_check_sub);
            }
            $_subscribe_data = $this->addSubscribeTemplate(
                $_access_token,
                "5545",
                array(10,8,4,9),
                "通知用户上传素材审核状态"
            );
            if($_subscribe_data["errcode"] != 0) {
                throw new \Exception($_subscribe_data["errmsg"], 402);
            }
            $_setting_id = $Setting = Setting::value("id");
            if(!SettingMessage::where("setting_id", $_setting_id)->update(array(
                "result_check_sub" => $_subscribe_data["priTmplId"]
            ))) {
                throw new \Exception("配置失败",402);
            }
            $_data = array("result_check_sub"=>$_subscribe_data["priTmplId"]);
            return response(["data"=>$_data]);
        }catch (\Exception $e) {
            return response(["message"=>$e->getMessage()],$e->getCode());
        }
    }

    /**
     * 获取订阅消息行业
     * @param string $_access_token
     * @return bool
     */
    private function getSubscribeClass($_access_token)
    {
        $_response = file_get_contents("https://api.weixin.qq.com/wxaapi/newtmpl/getcategory?access_token=".$_access_token);
        $_response = json_decode($_response,true);
        $_result = false;
        if($_response["errcode"] == 0) {
            $_result = $_response["data"];
        }
        return $_result;
    }

    /**
     * 删除订阅消息id
     */
    private function delSubscribeTpl($_access_token,$_tmp_id)
    {
        $Client = new Client();
        $_send_data = array(
            "form_params" => array("priTmplId" => $_tmp_id)
        );
        $response = $Client->request(
            "POST",
            "https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate?access_token=".$_access_token,
            $_send_data
        );
        $_result = false;
        if($response->getStatusCode() == 200) {
            $_content = json_decode($response->getBody(),true);
            if($_content['errmsg'] == 'ok' && $_content['errcode'] == 0) {
                $_result = true;
                unset($_content);
            }
        }
        return $_result;
    }

    /**
     * 选用添加订阅通知模板
     */
    private function addSubscribeTemplate($_access_token,$_tid,Array $_kid_list,$_scene_desc)
    {
        $_send_data = array(
           "form_params" => array(
               "tid" => $_tid,
               "kidList" => $_kid_list,
               "sceneDesc" => $_scene_desc
           )
        );
        $Client = new Client();
        $_response = $Client->request(
            "POST",
            "https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token=".$_access_token,
            $_send_data
        );
        $_result = false;
        if($_response->getStatusCode() == 200) {
            return json_decode($_response->getBody(),true);
        }
        return $_result;
    }
}
